package edu.ptit.jad.data;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MatrixUtils {

	public static double[][] readMatrix(String fileDir) throws Exception {

		File file = new File(fileDir);
		String line = "";

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				new FileInputStream(file), "UTF8"));

		int numbRows = Integer.parseInt(reader.readLine());
		int numbCols = Integer.parseInt(reader.readLine());

		double[][] matrix = new double[numbRows][numbCols];

		for (int i = 0; i < numbRows; i++) {

			line = reader.readLine().trim();

			String[] rows = line.split(" ");

			for (int j = 0; j < numbCols; j++) {

				matrix[i][j] = Double.parseDouble(rows[j]);

			}

		}

		return matrix;
	}

	public static void print(double[][] matrix) {

		int n = matrix.length;
		int m = matrix[0].length;
		for (int i = 0; i < n; i++) {

			for (int j = 0; j < m; j++)
				System.out.print(matrix[i][j] + " ");

			System.out.print("\n");

		}

	}

	public static void saveMatrix(double[][] matrix, String fileDir) throws Exception {
		int n = matrix.length;
		int m = matrix[0].length;
		File file = new File(fileDir);
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(file, false)));

		out.write(n+"");
		out.write("\n");
		out.write(m+"");
		out.write("\n");

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++)
				out.write(matrix[i][j] + " ");

			out.write("\n");

		}

		out.close();

	}
}
